package org.zjvis.datascience.common.dto;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.zjvis.datascience.common.constant.DataJsonConstant;
import org.zjvis.datascience.common.util.DozerUtil;
import org.zjvis.datascience.common.util.JsonParseUtil;
import org.zjvis.datascience.common.util.JwtUtil;
import org.zjvis.datascience.common.vo.TaskInstanceVO;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description 任务节点实例 TaskInstance 信息表，任务节点实例DTO
 * @date 2021-12-10
 */
@Data
public class TaskInstanceDTO extends BaseDTO {
    private Long id;
    private String parentId;
    private Long taskId;
    private Long pipelineId;
    private Long projectId;
    private Long userId;
    private String status;
    private String dataJson;
    private String sqlText;
    private String output;
    private Long sessionId;
    private String logInfo;
    private int runTimes;
    private String taskName;
    private Integer type;
    private Integer progress;
    private String applicationId;

    private LocalDateTime gmtRunning;

    public TaskInstanceDTO() {
    }

    public TaskInstanceDTO(TaskDTO task, Long sessionId) {
        this.setTaskId(task.getId());
        this.setPipelineId(task.getPipelineId());
        this.setProjectId(task.getProjectId());
        this.setSessionId(sessionId);
        this.setUserId(task.getUserId());
        this.setType(task.getType());
        JSONObject data = new JSONObject();
        data.put(DataJsonConstant.INSTANCE_JSON_HEADER, JSONObject.parseObject(task.getDataJson()));
        this.setDataJson(data.toJSONString());
        this.setGmtCreator(JwtUtil.getCurrentUserId());
        this.setGmtModifier(JwtUtil.getCurrentUserId());
        this.setTaskName(task.getName());
    }

    public TaskInstanceVO view() {
        TaskInstanceVO vo = DozerUtil.mapper(this, TaskInstanceVO.class);
        vo.setData(JSONObject.parseObject(this.getDataJson()));
        return vo;
    }

    public List<Long> getParentIdList() {
        if (StringUtils.isNotEmpty(this.parentId)) {
            String[] children = this.parentId.split(",");
            return Arrays.stream(children).map(Long::parseLong).collect(Collectors.toList());
        }
        return Lists.newArrayList();
    }

    /**
     * IDConstant.INSTANCE_PRECAUTION_ERROR
     *
     * @return
     */
    public boolean hasPrecautionaryError() {
        Object valueByKey = JsonParseUtil.getValueByKey("inputInfo.precautionaryError", this.dataJson, Object.class);
        if ((valueByKey instanceof String || valueByKey instanceof Exception)) {
            return true;
        }
        return false;
    }
}
